import { useEffect, useRef, useState } from "react";
import * as THREE from "three";
// @ts-expect-error: three/examples has no type declarations for OrbitControls
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
// @ts-expect-error: three/examples has no type declarations for FBXLoader
import { FBXLoader } from "three/examples/jsm/loaders/FBXLoader";
import {Select } from "antd";

const MODEL_PATH = "/modules/Happy.fbx";
const ANIMATION_PATHS = [
  { name: "Happy", path: "/modules/Happy.fbx" },
  { name: "Jab Cross", path: "/modules/Jab Cross.fbx" },
  { name: "Silly Dancing", path: "/modules/Silly Dancing.fbx" },
  { name: "Running Up Stairs", path: "/modules/Running Up Stairs.fbx" },
  { name: "Walk Strafe Left", path: "/modules/Walk Strafe Left.fbx" },
];

function MyAi() {
  const box = useRef<HTMLDivElement | null>(null);
  const mixerRef = useRef<THREE.AnimationMixer | null>(null);
  const modelRef = useRef<THREE.Group | null>(null);
  const [actions, setActions] = useState<{
    [key: string]: THREE.AnimationAction;
  }>({});
  const [currentAction, setCurrentAction] = useState<string>("Happy");

  useEffect(() => {
    // 获取父容器尺寸
    const getBoxSize = () => {
      if (box.current) {
        return {
          width: box.current.clientWidth,
          height: box.current.clientHeight,
        };
      }
      return { width: 300, height: 300 };
    };
    const { width, height } = getBoxSize();

    // 初始化场景和相机
    const clock = new THREE.Clock();
    const loadedActions: { [key: string]: THREE.AnimationAction } = {};
    const scene = new THREE.Scene();

    // 添加光源
    const ambientLight = new THREE.AmbientLight(0x404040);
    scene.add(ambientLight);
    const directionLight = new THREE.DirectionalLight(0xffffff, 1);
    directionLight.position.set(100, 200, 300);
    scene.add(directionLight);

    // 创建相机
    const camera = new THREE.PerspectiveCamera(
      70,
      width / height,
      0.1,
      800
    );
    camera.position.set(0, 120, 340);

    // 创建渲染器
    const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
    renderer.setSize(width, height);
    if (box.current) {
      box.current.innerHTML = "";
      box.current.appendChild(renderer.domElement);
    }
    // 创建控件
    const controls = new OrbitControls(camera, renderer.domElement);
    controls.enableDamping = true;

    // 加载主模型
    const loader = new FBXLoader();
    loader.load(MODEL_PATH, (object: THREE.Group) => {
      object.scale.set(1, 1, 1);
      // 数字人的位置调整
      object.position.x=-20
      object.position.y=-90
      scene.add(object);
      modelRef.current = object;
      mixerRef.current = new THREE.AnimationMixer(object);

      // 加载所有动画
      let loaded = 0;
      ANIMATION_PATHS.forEach(({ name, path }) => {
        loader.load(
          path,
          (anim: THREE.Group & { animations: THREE.AnimationClip[] }) => {
            if (
              anim.animations &&
              anim.animations.length > 0 &&
              mixerRef.current
            ) {
              const action = mixerRef.current.clipAction(anim.animations[0]);
              loadedActions[name] = action;
              if (name === "Happy") {
                action.play();
              }
            }
            loaded++;
            if (loaded === ANIMATION_PATHS.length) {
              setActions({ ...loadedActions });
            }
          }
        );
      });
    });

    // 渲染循环
    let frameId: number;
    const animate = () => {
      frameId = requestAnimationFrame(animate);
      controls.update();
      if (mixerRef.current) {
        mixerRef.current.update(clock.getDelta());
      }
      renderer.render(scene, camera);
    };
    animate();

    // 监听窗口变化
    const handleResize = () => {
      const { width, height } = getBoxSize();
      camera.aspect = width / height;
      camera.updateProjectionMatrix();
      renderer.setSize(width, height);
    };
    window.addEventListener("resize", handleResize);

    // 清理
    return () => {
      window.removeEventListener("resize", handleResize);
      cancelAnimationFrame(frameId);
      controls.dispose();
      renderer.dispose();
      if (scene && modelRef.current) {
        scene.remove(modelRef.current);
      }
      mixerRef.current = null;
      modelRef.current = null;
    };
  }, []);

  // 切换动画
  const handleChange = (name: string) => {
    console.log(name,actions[name],'切换动画')
    if (!actions[name]) return;
    Object.keys(actions).forEach((key) => {
      actions[key].stop();
    });
    actions[name].reset().play();
    setCurrentAction(name);
  };

  return (
    <div style={{ background: "transparent", height: "100%", width: "100%", position: "relative" }}>
      <div
        ref={box}
        style={{
          width: "100%",
          height: "100%",
          background: "transparent",
          zIndex: 1000,
          position: "relative"
        }}
      />
      <div style={{ position: "absolute", top: 80, left: 20 }}> 
        <Select
      defaultValue={currentAction}
      style={{ width: 120 ,zIndex:10000}}
      onChange={handleChange}
      options={[
        { value: 'Happy', label: 'Happy' },
        { value: 'Jab Cross', label: 'Jab Cross' },
        { value: 'Silly Dancing', label: 'Silly Dancing' },
        { value: 'Running Up Stairs', label: 'Running Up Stairs' },
        { value: 'Walk Strafe Left', label: 'Walk Strafe Left' },
      ]}
    />
      </div>
    </div>
  );
}

export default MyAi;
